<?php
/**
 * 上传
 */

namespace app\controller\v1;


use app\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\facade\Log;
use think\File;

class Upload
{
    protected $access_key = 'xZVrSnGVARhLJtqyEy9nJz-tOhI_79iGQkuXoYHB';
    protected $secret_key = 'aGigwhukPgxInAXNg3rGNLnWPZh_EPtRZ-ILBrzK';
    protected $bucket = 'juxuan';

    /**
     * 上传图片
     * @param Request $request
     * @return mixed
     */
    public function uploadImage(Request $request)
    {
        $position = 'default';
            $setting = self::_setting($position);
        if (empty($setting))
            return app('json')->json_error('配置出错');
        try {
//            $res = [];
            $files = $request->file('file'); //
            $uploadMgr = new UploadManager();
            $auth = new Auth($this->access_key, $this->secret_key);
            $token = $auth->uploadToken($this->bucket);
//            if (empty($request->param('type'))) { // 单图上传
            $url = $this->_before($files, $setting)->startUpload($files, $token, $uploadMgr, $position);
//            }
//            elseif ($request->param('type') == 'multiple') { // 多图上传
//                foreach ($files as $file) {
//                    $res[] = $this->_before($file, $setting)->startUpload($file, $token, $uploadMgr, $position);
//                }
//            }
            return app('json')->json_success('成功', ['url' => $url]);
        } catch (ValidateException $e) {
            return app('json')->json_error($e->getMessage());
        } catch (\Throwable $e) {
            return app('json')->json_error($e->getMessage());
        }
    }

    /**
     * 开始上传
     * @param $file
     * @param $token
     * @param $uploadMgr
     * @param $position
     * @return mixed
     * @throws \Exception
     */
    private function startUpload($file, $token, $uploadMgr, $position)
    {
        /**  @var File $file */
        $tmp_name = $file->getRealPath();
        $ext = $file->getMime();
        $ext = explode('/', $ext);
        $key = $position . '/' . md5(microtime(true) . mt_rand(1, 1e9)) . '.' . end($ext);
        /**  @var UploadManager $uploadMgr */
        list($ret, $error) = $uploadMgr->putFile($token, $key, $tmp_name);
        if ($error == null) {
            return $ret['key'];
        } else {
            throw new HttpException(500, '上传错误');
        }
    }

    /**
     * 前置操作
     * @param $file
     * @param array $setting
     * @return $this
     */
    private function _before($file, array $setting)
    {
        $validate = [
            'fileExt' => 'jpg,png,gif,jpeg',
            'fileMime' => 'image/jpeg,image/png,image/jpg,image/gif',
        ];
        if (isset($setting['size']))
            $validate['fileSize'] = $setting['size'] * 1040 * 1040;
        if (isset($setting['image']))
            $validate['image'] = $setting['image'];
        validate(['file' => $validate])->check(['file' => $file]);
        return $this;
    }

    /**
     * 上传设置
     * @param string $name
     * @return array
     */
    private static function _setting(string $name): array
    {
        $arr = [
            'avatar' => [
                'size' => 1,
                'image' => '512,512',
            ],
            'userBackground' => [
                'size' => 2,
                'image' => '512,512',
            ],
            'default' => ['default'],
        ];
        return isset($arr[$name]) ? $arr[$name] : [];
    }
}